package com.cztv.vote.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cztv.vote.bean.ReturnValBean;
import com.cztv.vote.bean.VoteRecord;
import com.cztv.vote.exception.VoteDealException;
import com.cztv.vote.service.VoteManager;

public class VoteServlet extends HttpServlet {
	private static final long serialVersionUID = -8698433209681275904L;
	private   VoteManager voteManager;
	
	@Required
	public void setVoteManager(VoteManager voteManager) {
		this.voteManager = voteManager;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		  ServletContext servletContext = config.getServletContext();
		  WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		  AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext.getAutowireCapableBeanFactory();
		  autowireCapableBeanFactory.configureBean(this, "voteManager");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		VoteRecord record=new VoteRecord();
		String voteId=request.getParameter("voteId");	
		int rid=0;
		String ip = request.getRemoteAddr();
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		if(voteId=="" || voteId==null)
			throw new VoteDealException("投票目标id不存在");
		else
			 rid=Integer.parseInt(voteId);
		
		ReturnValBean val=voteManager.isEnableVote(ip, rid);
		
		if(!val.isBoolVal()){
			out.print(val.getInfo());
			return;
		}
		
		val=voteManager.voteCheck(rid);
		if(!val.isBoolVal()){
			out.print(val.getInfo());
			return;
		}
		
		String voteIp=request.getRemoteAddr();
		record.setVoteId(rid);
		record.setVoteIp(voteIp);
		record.setVoteTime(System.currentTimeMillis());
		voteManager.vote(record);
	}

}
